package com.yuxi.auto;

import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;

/**
 * Created by yuxi on 16/11/5.
 */
public class AnalyzeActualSqlImpl extends AnalyzeActualSql {

    private MappedStatement mappedStatement;
    private Object parameterObject;
    private BoundSql boundSql;

    public AnalyzeActualSqlImpl(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
        this.boundSql = boundSql;
        this.mappedStatement = mappedStatement;
        this.parameterObject = parameterObject;
    }

    @Override
    public String getActualSql(String originalSql, TableSeg tableSeg) {
        String newSql = null;
        if (tableSeg == null)
            return newSql;
        String tableName = tableSeg != null ? tableSeg.tableName().trim() : "";

        //shardType="%5",shardBy="id"

        String shardType = tableSeg != null ? tableSeg.shardType().trim() : "";
        String shardBy = tableSeg != null ? tableSeg.shardBy().trim() : "";
        String suffix;
        suffix = getShardValue(shardType, shardBy);

        /************
         * mybatis获取值
         * todo add  by  yuxi
         * *************/
        //mybatis  获取parameter参数的方法
        MetaObject metaObject = parameterObject == null ? null : new Configuration()
                .newMetaObject(parameterObject);
        String[] str = metaObject.getGetterNames();
        for (String s : str) {
            System.out.println(metaObject.getValue(s));
        }
        if (suffix == null || suffix.equals("")) {

            return newSql;
        } else {
            //替换新表名
            String newTableName = tableName + "_" + suffix;
            //表名尽量保持唯一，不要与字段重名
            newSql = originalSql.replaceAll(tableName, newTableName);
        }
        return newSql;
    }

    private String getShardValue(String shardType, String shardBy) {
        return null;
    }


}
